package com.zjh.mf.mfcorelib.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

/**
 * 日志文件帮助类
 */

public class LogsHelper {
    private String logsFilePath;

    public LogsHelper(String logsFilePath) {
        this.logsFilePath = logsFilePath;

        File logsFile = new File(logsFilePath);
        try {
            if (!logsFile.getParentFile().exists()) {//上级文件夹不存在
                logsFile.getParentFile().mkdirs();
                logsFile.createNewFile();
            } else if (!logsFile.exists()) {//文件不存在
                logsFile.createNewFile();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 向已创建的文件中写入数据
     */
    public void print(String str) {
        FileWriter fw = null;
        BufferedWriter bw = null;
        String datetime = "";
        try {
            datetime = StringUtils.getTimeStrByLong(System.currentTimeMillis(),"yyyy-MM-dd hh:mm:ss");
            fw = new FileWriter(logsFilePath, true);
            // 创建FileWriter对象，用来写入字符流
            bw = new BufferedWriter(fw);// 将缓冲对文件的输出
            String myreadline = datetime + "[]" + str;
            bw.write(myreadline + "\n");// 写入文件
            bw.newLine();
            bw.flush(); // 刷新该流的缓冲
            bw.close();
            fw.close();
        } catch (Exception e) {
            e.printStackTrace();
            try {
                bw.close();
                fw.close();
            } catch (Exception e1) {
            }
        }
    }
}
